package com.itheima.reggie.controller;

import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.ShoppingCart;
import com.itheima.reggie.service.ShoppingCartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author Hu
 * 购物车
 * @version 1.0
 */
@RestController
@RequestMapping("/shoppingCart")
public class ShoppingCartController {

    //注入购物车service层依赖
    @Autowired
    private ShoppingCartService scs;

    /**
     * 删减数量出现未知错误
     *
     * @param shoppingCart
     * @return
     */
    @PostMapping("/sub")
    public R sub(@RequestBody ShoppingCart shoppingCart) {
        ShoppingCart sc = scs.sub(shoppingCart);
        if (sc != null) {
            return R.success(sc);
        } else {
            return R.error("删减数量出现未知错误");
        }
    }


    /**
     * 添加到购物车
     *
     * @param shoppingCart
     * @return
     */
    @PostMapping("/add")
    public R add(@RequestBody ShoppingCart shoppingCart) {
        ShoppingCart cart = scs.add(shoppingCart);
        if (cart != null) {
            return R.success(cart);
        } else {
            return R.error("添加出现未知错误");
        }

    }


    /**
     * 购物车展示
     *
     * @return
     */
    @GetMapping("/list")
    public R selectList() {
        try {
            List<ShoppingCart> cartList = scs.selectList();
            return R.success(cartList);
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("展示购物车页面出现未知错误");
        }
    }

    /**
     * 清空购物车
     *
     * @return
     */
    @DeleteMapping("/clean")
    public R deleteAll() {
        int row = scs.deleteAll();
        if (row > 0) {
            return R.success("清空成功");
        } else {
            return R.error("清空失败");
        }
    }
}
